#include <assert.h>
#include "thread_pool.h"

void assert_in_same_thread(struct event_loop *eloop)
{
    if (eloop->owner_thread_id != pthread_self())
    {
        exit(-1);
    }
}

struct thread_pool *thread_pool_new(struct event_loop *main_loop, int thread_num)
{
    struct thread_pool *pool = malloc(sizeof(struct thread_pool));
    pool->main_loop = main_loop;
    pool->position = 0;
    pool->thread_num = thread_num;
    pool->started = 0;
    pool->loop_threads = NULL;
    return pool;
}

void thread_pool_start(struct thread_pool *pool)
{
    assert(!pool->started);
    assert_in_same_thread(pool->main_loop);
    pool->started = 1;
    void *tmp;
    if (pool->thread_num <= 0)
    {
        return;
    }
    pool->loop_threads = malloc(pool->thread_num * sizeof(struct event_loop_thread));
    for (int i = 0; i < pool->thread_num; i++)
    {
        event_loop_thread_init(&pool->loop_threads[i], i);
        event_loop_thread_start(&pool->loop_threads[i]);
    }
}

// 在主线程中运行
struct event_loop *thread_pool_get_loop(struct thread_pool *pool)
{
    assert(pool->started);
    assert_in_same_thread(pool->main_loop);

    struct event_loop *selected = pool->main_loop;
    if (pool->thread_num > 0)
    {
        selected = pool->loop_threads[pool->position].eloop;
        if (++pool->position >= pool->thread_num)
        {
            pool->position = 0;
        }
    }
    return selected;
}